package com.cn.zkc2;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;

import java.util.List;

/**
 * Created by chenyuncong on 2019/4/1.
 */
public class ZKClientWatcherTest {
    /** zookeeper地址 */
    static final String connectString = "127.0.0.1:2181";
    /** session超时时间 */
    static final int sessionTimeout = 5000;

    public static void main(String[] args) throws InterruptedException {
        ZkClient zkClient = new ZkClient(new ZkConnection(connectString), 10000);
        // 监听当前节点和子节点的新增和删除，不监听修改操作
        zkClient.subscribeChildChanges("/super", new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> currentChild) throws Exception {
                System.out.println("--------------handleChildChange---------------");
                System.out.println("parentPath=" + parentPath);
                System.out.println("currentChild=" + currentChild);

            }
        });

        zkClient.subscribeDataChanges("/super", new IZkDataListener() {
            @Override
            public void handleDataChange(String path, Object data) throws Exception {
                System.out.println("修改节点 path=" + path + ", value=" + data);
            }

            @Override
            public void handleDataDeleted(String path) throws Exception {
                System.out.println("删除的节点 path" + path);
            }
        });


        Thread.sleep(3000);
        zkClient.createPersistent("/super");

        Thread.sleep(1000);


        zkClient.writeData("/super", "super new value");
        Thread.sleep(1000);

        zkClient.delete("/super");
        Thread.sleep(1000);

        zkClient.close();
    }
}
